package edu.ncsu.csc.ip.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import edu.ncsu.csc.ip.common.Log;
import edu.ncsu.csc.ip.common.NetworkUtils;
import edu.ncsu.csc.ip.common.Protocol;
import edu.ncsu.csc.ip.server.protocol.ProtocolServerImpl;

/**
 * Class <code></code>
 * 
 * 
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class RegistrationServerThread extends Thread {
	private Socket socket = null;
	private Protocol protocol = null;

	public RegistrationServerThread(Socket socket) {
		super("ServerThread");
		this.socket = socket;
		this.protocol = new ProtocolServerImpl(socket);
	}

	public void run() {

		try {
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));

			Log.println("{ Accepted connection from Client: ["
					+ NetworkUtils.getRemoteAdress(socket).getHostAddress() + "]");
			String inputLine, outputLine;
			String header = in.readLine();
			if (header != null) {
				inputLine = header + "\n" + in.readLine();
				Log.printMessage("Message From Client ["
						+ NetworkUtils.getRemoteAdress(socket).getHostAddress()
						+ "]", inputLine);
				outputLine = protocol.parseMessage(inputLine);
				Log.printMessage("Message To Client ["
						+ NetworkUtils.getRemoteAdress(socket).getHostAddress()
						+ "]", outputLine);
				out.println(outputLine);
			}
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
